#include <QApplication>
#include <QDebug>
#include "qtc.h"



// slot function connected to obj's someSignal 
void SubThread::someSlot() 
{ 
    QString msg; 
    msg.append(this->metaObject()->className()); 
    msg.append("::obj's thread is "); 
    //obj->thread: obj所属线程
    //qApp->thread: 应用主线程
    if (obj->thread() == qApp->thread()) 
    { 
        msg.append("MAIN thread;"); 
    } 
    else if (obj->thread() == this)  //this: 子线程对象自身
    { 
        msg.append("SUB thread;"); 
    } 
    else 
    { 
        msg.append("OTHER thread;"); 
    } 
    msg.append(" someSlot executed in ");
    //QThread::currentThread(): 执行当前函数的线程
    if (QThread::currentThread() == qApp->thread()) 
    { 
        msg.append("MAIN thread;"); 
    } 
    else if (QThread::currentThread() == this) 
    { 
        msg.append("SUB thread;"); 
    } 
    else 
    { 
        msg.append("OTHER thread;"); 
    } 
    qDebug() << msg; 
    quit(); 
}

//////////////////////////////////////////////////////// 
// class SubThread1 
//////////////////////////////////////////////////////// 
SubThread1::SubThread1(QObject* parent) 
    : SubThread(parent) //由主线程创建子线程对象
{ 
    obj = new SomeObject();//由主线程创建
    //自动连接
    connect(obj, SIGNAL(someSignal()), this, SLOT(someSlot())); 
} 
// reimplement run 
void SubThread1::run() 
{ 
    //自动(信号触发、receiver不同线程)----队列连接
    obj->callEmitSignal(); //子线程触发信号
#ifndef NOEXEC
    exec(); //进入当前线程的事件循环
#endif //NOEXEC
}

//////////////////////////////////////////////////////// 
// class SubThread2 
//////////////////////////////////////////////////////// 
SubThread2::SubThread2(QObject* parent) 
    : SubThread(parent) //由主线程创建子线程对象
{ 
    obj=0; 
} 
// reimplement run 
void SubThread2::run() 
{ 
    obj = new SomeObject(); //由当前子线程创建 
    //自动连接
    connect(obj, SIGNAL(someSignal()), this, SLOT(someSlot())); 
    //自动(信号触发、receiver不同线程)----队列连接
    obj->callEmitSignal(); //由子线程触发信
#ifndef NOEXEC
    exec(); 
#endif //NOEXEC
}

//////////////////////////////////////////////////////// 
// class SubThread3 
//////////////////////////////////////////////////////// 
SubThread3::SubThread3(QObject* parent) 
    : SubThread(parent) //由主线程创建子线程对象
{ 
    obj=0; 
} 
// reimplement run 
void SubThread3::run() 
{ 
    obj = new SomeObject(); //由当前子线程创建
    //显式指定直接连接
    connect(obj, SIGNAL(someSignal()), this, SLOT(someSlot()), 
            Qt::DirectConnection); 
    //信号触发、receiver不同，但强制为直接连接
    obj->callEmitSignal(); //由子线程触发信号 
#ifndef NOEXEC
    exec(); 
#endif //NOEXEC
}
